<script setup lang="ts">
import {
  ContainerStatus,
  Container,
  LabelSelector,
  Pod,
  ContainerState
} from "@/views/domain/kubeHud/api/k8s/types";
import { computed, onMounted, ref, toRef, watch } from "vue";
import PodContainerStatusCard from "./PodContainerStatusCard.vue";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { objectToList } from "@/views/domain/kubeHud/utils";

const { podRepo } = useK8SApi();

type Prop = {
  states?: ContainerStatus[];
  containers?: Container[];
  namespace?: string;
  nodeName?: string;
  labelSelector?: LabelSelector;
};

type ContainerMix = {
  status?: ContainerStatus;
  container?: Container;
};

const total = ref(0);
const nextToken = ref();
const loading = ref(false);

const labelSelector = computed(() => {
  const srcs = [
    props.nodeName ? `spec.nodeName=${props.nodeName}` : "",
    props.namespace ? `metadata.namespace=${props.namespace}` : "",
    ...objectToList(props.labelSelector).map(v => `${v.key}=${v.value}`)
  ];
  return srcs.filter(v => v !== "").join(",");
});

const loadPodList = async () => {
  loading.value = true;
  const { ok, data } = await podRepo.getPodList({
    namespace: props.namespace,
    labelSelector: labelSelector.value,
    continue: nextToken.value
  });

  if (ok) {
    states.value = [];
    containers.value = [];

    data.items.forEach(item => {
      states.value.push(...item.status.containerStatuses);
      containers.value.push(...item.spec.containers);
    });

    setupMixGroup();

    nextToken.value = data.metadata?.continue;
    total.value = data.metadata.remainingItemCount ?? data.items.length;
  }
  loading.value = false;
};

const props = defineProps<Prop>();
const containers = ref<Container[]>(props.containers);
const states = ref<ContainerStatus[]>(props.states);

const mixWrapper = ref<{ [key: string]: ContainerMix }>();

const setupMixGroup = () => {
  if (
    !states.value ||
    !containers.value ||
    states.value.length === 0 ||
    containers.value.length === 0
  ) {
    return [];
  }

  mixWrapper.value = {};
  states.value.forEach(status => {
    mixWrapper.value[status.name] = {
      status
    };
  });

  containers.value.forEach(container => {
    mixWrapper.value[container.name].container = container;
  });
};

onMounted(() => {
  if (props.states && props.containers) {
    setupMixGroup();
  } else {
    loadPodList();
  }
});

watch(props.containers, n => {
  containers.value = n;
  setupMixGroup();
});

watch(props.states, n => {
  states.value = n;
  setupMixGroup();
});
</script>

<template>
  <el-space direction="vertical" fill>
    <PodContainerStatusCard
      v-for="mix in mixWrapper"
      :key="mix.status.name"
      :c-state="mix.status"
      :container="mix.container"
    />
  </el-space>
</template>
<style lang="scss" scoped></style>
